package com.dhcc.bpm.modules.content.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dhcc.bpm.common.annotation.Log;
import com.dhcc.bpm.common.enums.BusinessType;
import com.dhcc.bpm.modules.api.entity.Product;
import com.dhcc.bpm.modules.api.service.IApiService;
import com.dhcc.bpm.modules.api.service.IProductService;
import com.dhcc.bpm.modules.common.entity.Plupload;
import com.dhcc.bpm.modules.common.service.IPluploadService;
import com.dhcc.bpm.modules.content.entity.DocDirectory;
import com.dhcc.bpm.modules.content.mapper.DocDirectoryMapper;
import com.dhcc.bpm.modules.content.service.IDocDirectoryService;
import com.dhcc.bpm.modules.content.vo.DocDirectoryVO;
import com.dhcc.bpm.modules.content.wrapper.DocDirectoryWrapper;
import com.dhcc.bpm.modules.system.entity.User;
import com.dhcc.bpm.modules.system.service.ISerialNumberService;
import com.dhcc.bpm.modules.system.service.IUserService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import me.zhyd.oauth.utils.StringUtils;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * @ClassName DocDirectoryController
 * @Description 文档目录 控制器
 * @Author lijiacheng
 * @Date 2020/2/21 14:16
 * @Version V1.0
 * @Copyright: 2020 东华软件 . All rights reserved.
 */

@RestController
@AllArgsConstructor
@RequestMapping("bpm-content/docdirectory")
@Api(value = "文档目录", tags = "文档目录接口")
public class DocDirectoryController extends BladeController {

    private IDocDirectoryService docDirectoryService;

    private ISerialNumberService serialNumberService;

    private DocDirectoryMapper docDirectoryMapper;

    private IUserService userService;

    private IPluploadService pluploadService;

    private IApiService apiService;

    private IProductService productService;

    /**
     * 详情
     */
    @ApiLog("文档模块表详情")
    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情", notes = "传入docDirectory")
    public R<DocDirectoryVO> detail(DocDirectory docDirectory) {
        DocDirectory detail = docDirectoryService.getOne(Condition.getQueryWrapper(docDirectory));
        DocDirectoryVO docDirectoryVO = new DocDirectoryVO();
        BeanUtil.copy(detail, docDirectoryVO);
        if (!"#".equals(detail.getUrl()) && StringUtils.isNotEmpty(detail.getUrl())) {
//			Plupload plupload = new Plupload();
//			plupload.setFileFullpath(detail.getUrl());
//			plupload = pluploadService.getOne(Condition.getQueryWrapper(plupload));
            Plupload plupload = pluploadService.selectByUrl(detail.getUrl());
            if (plupload != null) {
                docDirectoryVO.setFileFullPath(detail.getUrl());
                docDirectoryVO.setOpcPluploadId(plupload.getId());
                docDirectoryVO.setFileRealName(plupload.getFileRealname());
            }
        }
        return R.data(docDirectoryVO);
    }

    /**
     * 分页 文档目录
     */
    @ApiLog("文档模块表列表")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "docName", value = "文档名称", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "docCode", value = "文档编号", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "docType", value = "文档类型", paramType = "query", dataType = "string")
    })
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页", notes = "传入docDirectory")
    public R<List<DocDirectoryVO>> list(@ApiIgnore @RequestParam Map<String, Object> docDirectory) {
        List<DocDirectory> list = docDirectoryService.list(Condition.getQueryWrapper(docDirectory, DocDirectory.class).lambda().orderByAsc(DocDirectory::getOrderNum));
        for (DocDirectory directory : list) {
            User user = userService.getById(directory.getCreateUser());
            if (user != null) {
                directory.setPerms(user.getAccount());
            } else {
                directory.setPerms("");
            }
        }
        return R.data(DocDirectoryWrapper.build().listDocNodeVO(list));
    }

    /**
     * 自定义分页 文档目录
     */
    @ApiLog("文档模块表分页")
    @GetMapping("/page")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "分页", notes = "传入docDirectory")
    public R<IPage<DocDirectoryVO>> page(DocDirectoryVO docDirectory, Query query) {
        IPage<DocDirectoryVO> pages = docDirectoryService.selectDocDirectoryPage(Condition.getPage(query), docDirectory);
        return R.data(pages);
    }

    /**
     * 新增 文档目录
     */
    @ApiLog("文档模块表保存")
    @PostMapping("/save")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "传入docDirectory")
    @Log(title = "文档中心", businessType = BusinessType.INSERT)
    public R save(@Valid @RequestBody DocDirectory docDirectory) {
        return R.status(docDirectoryService.save(docDirectory));
    }

    /**
     * 修改 文档目录
     */
    @ApiLog("文档模块表更新")
    @PostMapping("/update")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "修改", notes = "传入docDirectory")
    @Log(title = "文档中心", businessType = BusinessType.UPDATE)
    public R update(@Valid @RequestBody DocDirectory docDirectory) {
        return R.status(docDirectoryService.updateById(docDirectory));
    }

    /**
     * 新增或修改 文档目录
     */
    @ApiLog("文档模块表提交")
    @PostMapping("/submit")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "新增或修改", notes = "传入docDirectory")
    @Log(title = "文档中心", businessType = BusinessType.INSERT)
    @Transactional(rollbackFor = Exception.class)
    public R submit(@Valid @RequestBody DocDirectoryVO docDirectory) {
        if (docDirectory.getId() == null) {
            // 设置文档编号
            String code = serialNumberService.generateSerialNumberByModelCode("opc_doc_directory");
            docDirectory.setDocCode(code);
        } else {
            //更新api文档
            if ("3".equals(docDirectory.getDocType()) && StringUtils.isNotEmpty(docDirectory.getRelateId())) {
                com.dhcc.bpm.modules.api.entity.Api api = new com.dhcc.bpm.modules.api.entity.Api();
                api.setId(Long.valueOf(docDirectory.getRelateId()));
                api.setBusId(docDirectory.getOpcPluploadId());
                apiService.updateById(api);
            }
            // 更新应用产品文档
            if ("2".equals(docDirectory.getDocType()) && StringUtils.isNotEmpty(docDirectory.getRelateId())) {
                Product prdt = new Product();
                prdt.setId(Long.valueOf(docDirectory.getRelateId()));
                prdt.setFilePath(docDirectory.getOpcPluploadId().toString());
                productService.updateById(prdt);
            }
        }
        return R.status(docDirectoryService.saveOrUpdate(docDirectory));
    }


    /**
     * 删除 文档目录
     */
    @ApiLog("文档模块表删除")
    @PostMapping("/remove")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "逻辑删除", notes = "传入ids")
    @Log(title = "文档中心", businessType = BusinessType.DELETE)
    public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
        List<Long> id = Func.toLongList(ids);
        for (Long i : id) {
            DocDirectory docDirectory = docDirectoryService.getById(i);
            Plupload plupload1 = new Plupload();
            plupload1.setFileFullpath(docDirectory.getUrl());
            QueryWrapper<Plupload> queryWrapper = Condition.getQueryWrapper(plupload1);
            plupload1 = pluploadService.getOne((queryWrapper.lambda().eq(Plupload::getFileFullpath, plupload1.getFileFullpath())));
            if (plupload1 != null) {
                pluploadService.fileDelete(plupload1.getId());
            }
        }
        return R.status(docDirectoryService.deleteLogic(id));
    }


    /**
     * 获取文档目录树形结构
     */
    @ApiLog("文档模块表树")
    @GetMapping("/tree")
    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "文档目录树形结构", notes = "树形结构")
    public R<List<DocDirectoryVO>> tree() {
        List<DocDirectoryVO> tree = docDirectoryService.tree();
        return R.data(tree);
    }

    /**
     * 查询文档目录
     *
     * @param opcDirectoryCode
     * @return
     */
    @ApiLog("文档模块表查询")
    @PostMapping("/selectDoc")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "查询文档目录", notes = "传入文档目录编号")
    public R<DocDirectory> selectDocName(@ApiParam(value = "主键", required = true) @RequestParam String opcDirectoryCode) {
        DocDirectory docDirectory = docDirectoryMapper.selectParentByChildcode(opcDirectoryCode);
        return R.data(docDirectory);
    }


    /**
     * 新增或修改 文档目录
     */
    @ApiLog("文档上下线")
    @PostMapping("/changeStatus")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "文档上下线", notes = "传入docDirectory")
    @Log(title = "文档上下线", businessType = BusinessType.UPDATE)
    public R changeStatus(@Valid @RequestBody DocDirectory docDirectory) {
        DocDirectory docDirectory1 = docDirectoryService.getById(docDirectory.getId());
        docDirectory.setDocCode(docDirectory1.getDocCode());
        int a = docDirectoryMapper.updateByDocCode(docDirectory);
        if (a > 0) {
            return R.status(true);
        }
        return R.status(false);
    }
}
